
#include "MotionResponseServer.h"

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <thread>
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"


#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <boost/array.hpp>
#include <queue>
#include "RealTimeData.h"


MotionResponseServer::MotionResponseServer()
    : isRun(false)
{
	dataM = RealTimeData::instance();
}

MotionResponseServer::~MotionResponseServer()
{

}

void MotionResponseServer::run()
{
    isRun = true;
    while (isRun)
    {
        try
        {
            if (MotionTaskQueue::instance()->reqData.size() > 0)
            {
				
                Data_Request req = MotionTaskQueue::instance()->reqData.front();
				
				MotionTaskQueue::instance()->mtxReqData.lock();
                MotionTaskQueue::instance()->reqData.pop();
				MotionTaskQueue::instance()->mtxReqData.unlock();
					
                std::string retStr = GenSendStr(&req);
				char lenStr[16];
				sprintf(lenStr, "%010d", retStr.length());
				//retStr = lenStr + retStr;
				int sendLen = boost::asio::write(*req.reqSocket, boost::asio::buffer(lenStr, 10));
                sendLen = boost::asio::write(*req.reqSocket, boost::asio::buffer(retStr.c_str(), retStr.length()));
                std::cout << "Result Json:<" << retStr << ">" << std::endl;
                if (sendLen >= retStr.length())
                {
					std::cout << "Send Result Success, Send:<" << retStr.length() << ">, Real Send:<" << retStr << ">" << std::endl;
                    //req.reqSocket->close();
                    //delete req.reqSocket;
                }
                else
                {
                    std::cout << "Send Error:<" << sendLen << ">" << std::endl;
                }
                
                std::this_thread::sleep_for(std::chrono::milliseconds(15));
            }

        }
        catch (std::exception& e)
        {
            std::cerr << "Exception: " << e.what() << std::endl;
        }
    }
}

void MotionResponseServer::stop()
{
    isRun = false;
}

std::string MotionResponseServer::GenSendStr(Data_Request* r)
{
    std::string ret = "";
	std::string keyStr = "";

    rapidjson::StringBuffer buf;
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buf);
    writer.StartObject();

    //writer.Key("result_data");
    //writer.StartObject();
	char value[32];
    for (int i = 0; i < r->DataNameList.size(); i++)
    {
		keyStr = r->DataNameList[i];
        writer.Key(keyStr.c_str()); 
		sprintf(value, "%.4f", dataM->currentData[keyStr]);
		writer.String(value);
    }
	
    writer.EndObject();
    ret = buf.GetString();

    return ret;
}

